import React from 'react';
import { NavBar, Icon } from "antd-mobile"
import Css from "./index.module.scss"
import { BMap } from "../../utils/baiduMap"
import { connect } from "react-redux"
import { request, baseURL } from "../../utils/request"
import HouseItem from "../../components/houseItem"
let map = null;
class MapFound extends React.Component {
    state = {
        houselist: [],
        showDetail: false
    }
    //页面挂载完毕执行的函数
    async componentDidMount() {
        // 拿到城市名称
        const cityName = this.props.cityName;
        map = new BMap.Map("container");
        //  地图绑定拖动事件
        map.addEventListener('dragstart', () => {
            //隐藏房子列表
            this.setState({ showDetail: false });
        })
        //平移缩放控件
        map.addControl(new BMap.NavigationControl());
        //比例尺
        map.addControl(new BMap.ScaleControl());

        // 异步请求拿到城市id
        const id = (await request.get("/area/info?name=" + '广州')).data.body.value;
        this.drawHouse(id, cityName);

    }
    getMapInfo = (function () {
        //第一步，在第一个方法中声明你要缓存的数据
        let list = [
            { times: 1, cls: "circle", zoom: 11 },
            { times: 2, cls: "circle", zoom: 13 },
            { times: 3, cls: "rect", zoom: 15 },
        ]
        let currentIndex = -1;
        return function () {
            currentIndex++;
            return list[currentIndex];
        }
    })()
    drawHouse = async (id, address) => {

        const mapInfo = this.getMapInfo();

        map.centerAndZoom(address, mapInfo.zoom);
        const houseList = (await request.get("/area/map?id=" + id)).data.body;

        houseList.forEach(v => {
            // 生成房源对应的点对象
            // 百度地图API功能
            var point = new BMap.Point(v.coord.longitude, v.coord.latitude);

            var opts = {
                position: point,    // 指定文本标注所在的地理位置
                offset: new BMap.Size(0, 0)    //设置文本偏移量
            }
            const content = `<div class="${Css[mapInfo.cls]}"> <span>${v.label}</span>
            <span>${v.count}套</span></div>`
            var label = new BMap.Label(content, opts);  // 创建文本标注对象
            label.setStyle({
                border: 'none',
                backgroundColor: "transparent",
                fontFamily: "微软雅黑"
            });

            /// 百度地图的自己的封装元素的 事件函数  不支持 async !!
            //给label绑定点击事件
            label.addEventListener('click', () => {
                const newId = v.value;
                console.log(newId)
                const newPoint = new BMap.Point(v.coord.longitude, v.coord.latitude);

                //判断是不是到了最后一个层级了
                if (mapInfo.times === 3) {
                    // 显示房屋列表
                    this.setState({ showDetail: true })
                    this.getHouseList(newId);
                } else {
                    //    清除之前的覆盖物 显示当前点击的label结果
                    setTimeout(() => {
                        map.clearOverlays();
                    }, 0)
                    this.drawHouse(newId, newPoint);
                }

            })
            //把设置到的文本添加地图上
            map.addOverlay(label);

        });

    }
    // 获取房源数据
    getHouseList = async (id) => {
        const houselist = (await request.get('/houses?cityId=' + id)).data.body.list;
        console.log(houselist);
        this.setState({ houselist })

    }
    render() {
        const { showDetail, houselist } = this.state;
        return (
            <div>
                <div className={Css.found_nav}>
                    <NavBar
                        mode="light"
                        icon={<Icon type="left" />}
                        onLeftClick={() => this.props.history.goBack()}
                    >地图找房</NavBar>
                </div>
                <div className={Css.found_main}>
                    {/* 地图渲染开始 */}
                    <div className={Css.main_container} id="container">
                        {/* //地图容器 */}
                    </div>
                    {/* 地图渲染结束 */}
                    {/* 房子列表开始 */}
                    {showDetail && <div className={[Css.house_list, Css.slideup].join(' ')}>
                        {/* //房子内容 */}
                        <div className={Css.house_list_title}>
                            <span>房屋列表</span>
                            <span>更多房源</span>
                        </div>
                        <div className={Css.house_list_content}>
                            {houselist.map((v, i) => <div key={i} className={Css.house_list_item} >
                                <HouseItem houseItem={v} />
                            </div>)}
                        </div>
                    </div>}
                    {/* 房子列表结束 */}
                </div>
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    cityName: state.CityReducer.cityname.name
})
export default connect(mapStateToProps)(MapFound);